package com.qs.sckill.controller;

import com.qs.sckill.config.redis.key.GoodsKey;
import com.qs.sckill.entity.Goods;
import com.qs.sckill.entity.User;
import com.qs.sckill.result.Result;
import com.qs.sckill.service.GoodsService;
import com.qs.sckill.service.RedisService;
import com.qs.sckill.service.UserService;
import com.qs.sckill.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController{

    @Resource
    private UserService userService;

    @Resource
    private RedisService redisService;

    @Resource
    private GoodsService goodsService;


    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;


    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 优化商品列表请求（页面级缓存，将整个列表页存储在redis中，设置失效时间为60s）
     */
    @RequestMapping(value = "/to_list", produces = "text/html")
    @ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response, Model model, User user) {
        if (user == null) {
            return "用户不存在！";
        }

        model.addAttribute("user", user);

        //获取缓存
        String html = redisService.get(GoodsKey.goodsList, "", String.class);
        if (StringUtils.isNotBlank(html)) {
            return html;
        }

        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
        WebContext webContext = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", webContext);
        if (StringUtils.isNotBlank(html)) {
            redisService.set(GoodsKey.goodsList, "", html);
        }

        return html;
    }

    /**
     * 用于带参数压测（测试接口）
     *
     * @param user 用户信息
     */
    @RequestMapping(value = "/userinfo")
    @ResponseBody
    public Result<User> userInfo(User user) {
        if (user == null) {
            System.out.println("用户不存在！");
        }

        return Result.success(user);
    }

    @GetMapping(value = "/to_detail/{goodsId}")
    public String detail(Model model, User user,
                         @PathVariable("goodsId") String goodsId) {

        //未登录，则登录
        if (user == null) {
            return "redirect:/login/to_login";
        }

        model.addAttribute("user", user);
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        model.addAttribute("goods", goods);

        long startTime = goods.getStartDate().getTime();
        long endTime = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        //计算和获取秒杀活动状态
        String sckillStatus = "0";
        int remainSeconds = 0;
        //秒杀还没有开始，倒计时
        if (now < startTime) {
            remainSeconds = (int) ((startTime - now) / 1000);
        } else if (now > endTime) {  //秒杀已经结束
            sckillStatus = "2";
            remainSeconds = -1;
        } else {  //秒杀进行中
            sckillStatus = "1";
        }

        model.addAttribute("sckillStatus", sckillStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        return "goods_detail";
    }
}
